import api from "@/api";
import {getRouters, setRouters} from "@/api/auth";

/**
 * 初始菜单
 * @param router
 * @param store
 * @returns {Promise<void>}
 */
export const initMenu = async (router, store) => {
    // if (store.getters.app.routes.length > 0)
    //     return
    //console.log(router, "routes1111111111111")
    let res
    if (!getRouters()){
        res = await api.user.getMenusByAdminId();
    }else{
        res = JSON.parse(getRouters())
    }
    if (res.code == 200) {
        setRouters(res)
        let routes = formatRoutes(res.data)
        router.addRoutes(routes)
        store.commit('app/setRoutes', routes)
        //console.log(router.options.routes, "routes")
    }
}

export const formatRoutes = (routes) => {
    let fmtRoutes = []
    for (const item of routes) {
        let {
            id,
            path,
            component,
            name,
            iconCls,
            children,
        } = item
        if (children && children instanceof Array) {
            // 递归
            children = formatRoutes(children)
        }
        let fmRouter = {
            id: id,
            path: path,
            name: name,
            iconCls: iconCls,
            children: children,
        }
        fmRouter.component = layout();

        function layout() {
            // return await import(`@/views${path+'/'+component}.vue`)
            return require(`@/views${path + '/' + component}.vue`).default
        }

        fmtRoutes.push(fmRouter)
    }
    return fmtRoutes
}
